package com.servicedemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.NotificationCompat;

public class MyService extends Service {
    private String data = "本进程数据";
    private boolean isRuning;//控制线程是否运行
    @Override
    public IBinder onBind(Intent intent) {
        //根据aidl生成的接口
        IRemoteBinder.Stub binder = new IRemoteBinder.Stub() {
            @Override
            public void setData(String data) throws RemoteException {
                MyService.this.data = data;//修改“本进程数据”
            }
        };
        return binder;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        isRuning = true;
        new Thread() {
            @Override
            public void run() {
                while (isRuning) {
                    System.out.println(MyService.this.data);//在新开线程，每秒输出一次
                     if(MyService.this.data.equals("aaa")){
                         sendNotification();
                         isRuning=false;

                         return;
                     }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    @Override
    public void onDestroy() {
        isRuning = false;
        super.onDestroy();
    }

    private  void sendNotification() {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 999, intent, 0);
        Notification notification= new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("服务发送的通知")
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.hert))
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(777,notification);
    }
}
